package com.etc.order.consumer.controller;

import com.etc.order.common.domain.OrderDetail;
import com.etc.order.common.domain.OrderMaster;
import com.etc.order.common.domain.ProductCategory;
import com.etc.order.common.domain.ProductInfo;
import com.etc.order.common.dto.*;
import com.etc.order.common.service.OrderDetailService;
import com.etc.order.common.service.OrderMasterService;
import com.etc.order.common.service.ProductCategoryService;
import com.etc.order.common.service.ProductInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class OrderController {

    @Resource
    @Reference
    private ProductInfoService productInfoService;

    @Resource
    @Reference
    private OrderMasterService orderMasterService;

    @Resource
    @Reference
    private ProductCategoryService productCategoryService;

    @Resource
    @Reference
    private OrderDetailService orderDetailService;

    /**
     * 商品列表
     */
    @GetMapping("/sell/product/list")
    @ResponseBody
    public SimpleDTO productList(String productIdOrName, int pageIndex, int pageSize){
        List<Object> productInfos = new ArrayList<>();
        int totalCount;
        if (productIdOrName != null && !productIdOrName.equals("")) {
            productInfos.addAll(productInfoService.findByProductName(productIdOrName, pageIndex, pageSize));
            totalCount = productInfoService.getTotalCount(productIdOrName);
            if (productInfos.size() == 0) {
                ProductInfo info = productInfoService.getOne(productIdOrName);
                if (info != null) {
                    productInfos.add(info);
                    totalCount = 1;
                }
            }
        } else {
            productInfos.addAll(productInfoService.findAll(pageIndex, pageSize));
            totalCount = productInfoService.getTotalCount("");
        }
        int totalPage = totalCount / pageSize;
        productInfos.add(totalCount % pageSize == 0 ? totalPage : totalPage + 1);
        return new SimpleDTO(0, "成功", productInfos);
    }

    @GetMapping("/sell/product/save")
    @ResponseBody
    public SimpleDTO saveProduct(String productId,
                                 String productName,
                                 int categoryType,
                                 double productPrice,
                                 @RequestParam(required = false) int productStock,
                                 String productDescription,
                                 @RequestParam(required = false) String productIcon,
                                 @RequestParam(required = false) int productStatus,
                                 boolean forUpdate) throws UnsupportedEncodingException {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setProductId(productId);
        productInfo.setProductName(URLDecoder.decode(productName, "UTF-8"));
        productInfo.setCategoryType(categoryType);
        productInfo.setProductPrice(new BigDecimal(productPrice));
        if (!forUpdate) productInfo.setProductStock(productStock);
        productInfo.setProductDescription(productDescription);
        if (forUpdate) productInfo.setProductIcon(productIcon);
        if (forUpdate) productInfo.setProductStatus(productStatus);
        if (productInfoService.save(productInfo) > 0) {
            return new SimpleDTO(0, "成功", null);
        } else {
            return new SimpleDTO(1, "失败", null);
        }
    }

    @GetMapping("/sell/product/delete")
    @ResponseBody
    public SimpleDTO deleteProduct(String productId) {
        if (productInfoService.delete(productId) > 0) {
            return new SimpleDTO(0, "成功", null);
        } else {
            return new SimpleDTO(1, "失败", null);
        }
    }

    @GetMapping("/dish.html")
    public String dish() {
        return "dish";
    }

    /**
     * 创建订单
     * @param userInfoDTO
     * @return
     */
    @PostMapping("/sell/buyer/order/create")
    @ResponseBody
    public SimpleDTO orderCreate(UserInfoDTO userInfoDTO){

        //获取数据存入对象
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setBuyerName(userInfoDTO.getName());
        orderMaster.setBuyerPhone(userInfoDTO.getPhone());
        orderMaster.setBuyerAddress(userInfoDTO.getAddress());
        //获取数据中List的值存入List<OrderDetail>
        List<OrderDetail> orderDetails = new ArrayList<>();
        for(int i=0; i<userInfoDTO.getItems().size(); i++){
            orderDetails.get(i).setProductId(userInfoDTO.getItems().get(i).getProductId());
            orderDetails.get(i).setProductQuantity(userInfoDTO.getItems().get(i).getProductQuantity());
        }

        //插入数据
        boolean result = orderMasterService.createOrderMaster(orderMaster, orderDetails);

        //判断是否插入成功
        if(!result){
            return new SimpleDTO(1, "失败", new OrderIdDTO("0"));
        }

        return new SimpleDTO(0, "成功", new OrderIdDTO());//插入时orderId的获取
    }

    /**
     * 订单列表
     */
    @GetMapping("/sell/buyer/order/list")
    @ResponseBody
    public SimpleDTO orderList(String nameOrId, int pageIndex, int pageSize){

        //调用方法
        List<OrderMaster> orderMasterListByName;
        int totalCount;
        if (nameOrId != null && !nameOrId.equals("")) {
            orderMasterListByName = orderMasterService.findOrderMasterListByName(nameOrId, pageIndex, pageSize);
            totalCount = orderMasterService.getTotalCount(nameOrId);
            if (orderMasterListByName.size() == 0) {
                OrderMaster order = orderMasterService.findByOrderId(nameOrId);
                if (order != null) {
                    orderMasterListByName.add(order);
                    totalCount = 1;
                }
            }
        } else {
            orderMasterListByName = orderMasterService.findAll(pageIndex, pageSize);
            totalCount = orderMasterService.getTotalCount("");
        }

        //获取的list转换为List<OrderMasterDTO>
        List<Object> orderMasterDTOList = new ArrayList<>();
        for (OrderMaster orderMaster : orderMasterListByName) {
            OrderMasterDTO orderMasterDTO = new OrderMasterDTO();
            orderMasterDTO.setOrderId(orderMaster.getOrderId());
            orderMasterDTO.setBuyerName(orderMaster.getBuyerName());
            orderMasterDTO.setBuyerPhone(orderMaster.getBuyerPhone());
            orderMasterDTO.setBuyerAddress(orderMaster.getBuyerAddress());
            orderMasterDTO.setOrderAmount(orderMaster.getOrderAmount());
            orderMasterDTO.setOrderStatus(orderMaster.getOrderStatus());
            orderMasterDTO.setPayStatus(orderMaster.getPayStatus());
            orderMasterDTO.setCreateTime(orderMaster.getCreateTime());
            orderMasterDTO.setUpdateTime(orderMaster.getUpdateTime());
            orderMasterDTO.setOrderDetailList(orderDetailService.findOrderDetailByOrderId(orderMaster.getOrderId(), 0, 99));//通过orderId来查询详细信息
            orderMasterDTOList.add(orderMasterDTO);
        }
        int totalPage = totalCount / pageSize;
        orderMasterDTOList.add(totalCount % pageSize == 0 ? totalPage : totalPage + 1);
        //成功
        return new SimpleDTO(0, "成功", orderMasterDTOList);
    }

    @GetMapping("/order.html")
    public String order() {
        return "order";
    }

    @GetMapping("/order_detail.html")
    public String orderDetail() {
        return "order_detail";
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/sell/buyer/order/detail")
    @ResponseBody
    public SimpleDTO orderDetail(String detailOrOrderId, int pageIndex, int pageSize){
        List<OrderDetail> orderDetailList;
        int totalCount;
        if (detailOrOrderId != null && !detailOrOrderId.equals("")) {
            orderDetailList = orderDetailService.findOrderDetailByOrderId(detailOrOrderId, pageIndex, pageSize);
            totalCount = orderDetailService.getTotalCount(detailOrOrderId);
            if (totalCount == 0) {
                orderDetailList.clear();
                OrderDetail detail = orderDetailService.getOne(detailOrOrderId);
                if (detail != null) {
                    orderDetailList.add(detail);
                    totalCount = 1;
                }
            }
        } else {
            orderDetailList = orderDetailService.findAll(pageIndex, pageSize);
            totalCount = orderDetailService.getTotalCount("");
        }
        //调用方法
        List<Object> orderDetailDTOs = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
            orderDetailDTO.setDetailId(orderDetail.getDetailId());
            orderDetailDTO.setOrderId(orderDetail.getOrderId());
            orderDetailDTO.setProductIcon(orderDetail.getProductIcon());
            orderDetailDTO.setProductId(orderDetail.getProductId());
            orderDetailDTO.setProductName(orderDetail.getProductName());
            orderDetailDTO.setProductPrice(orderDetail.getProductPrice());
            orderDetailDTO.setProductQuantity(orderDetail.getProductQuantity());
            orderDetailDTO.setProductImage(orderDetail.getProductIcon());
            orderDetailDTOs.add(orderDetailDTO);
        }
        int totalPage = totalCount / pageSize;
        orderDetailDTOs.add(totalCount % pageSize == 0 ? totalPage : totalPage + 1);

        return new SimpleDTO(0, "成功", orderDetailDTOs);
    }

    /**
     * 取消订单
     * @param buyerNameDTO
     * @return
     */
    @PostMapping("/sell/buyer/order/cancel")
    @ResponseBody
    public SimpleDTO orderCancel(BuyerNameDTO buyerNameDTO){
        SimpleDTO simpleDTO = new SimpleDTO();

        return simpleDTO;
    }


    //支付订单
}
